package com.situ.allaia.controller;

import com.situ.allaia.common.Global;
import com.situ.allaia.model.*;
import com.situ.allaia.service.CartService;
import com.situ.allaia.service.CategoryService;
import com.situ.allaia.service.GoodService;
import com.situ.allaia.util.PaginateInfo;
import com.situ.allaia.util.TreeUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping
public class IndexController {
    private final CategoryService categoryService;
    private final GoodService goodService;
    private final CartService cartService;

    public IndexController(CategoryService categoryService, GoodService goodService, CartService cartService) {
        this.categoryService = categoryService;
        this.goodService = goodService;
        this.cartService = cartService;
    }

    @RequestMapping({"/","/index"})
    public String index(Map<String,Object> map, HttpSession session){
        List<Category> categories = categoryService.findAll();
        System.out.println(categories);
        TreeUtils.TreeNode<Category,Integer> root = TreeUtils.buildTreeByParentId(categories, Category::getParentId);

        //下面的categories是index中的each中的
        map.put("categories",root.getChildren());


        //查询出8件商品显示在首页
        GoodSearchBean gsb = new GoodSearchBean();
        gsb.setIsBestSeller(true);  //查询热销的
        gsb.setIsTakeOff(false);
        gsb.setIsDel(false);
        PaginateInfo pi = new PaginateInfo(1,8);
        List<Good> goodList = goodService.findAll(gsb,pi);



        User user = Global.findUser(session);
        if (user!=null){
            List<CartItem> items = cartService.findByUserId(user.getId());
            map.put("items", items);
        }

        map.put("goods",goodList);
        return "index";
    }
}
